
package com.eva.android.widget;

import android.app.Activity;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.ProgressBar;

import com.x52im.rbchat.R;
import com.x52im.rbchat.utils.IntentFactory;

import java.util.ArrayList;

import androidx.annotation.RequiresApi;

/**
 * 一个通用的网页看看界面。
 *
 * @author Lu, Jack Jiang
 * @since 6.0
 */
public class CommonWebActivity2 extends ActivityRoot
{
    private final static String TAG = CommonWebActivity2.class.getSimpleName();

    /** 更多选项弹出框类 */
    private MorenChoicePopWindow menuWindowForMore = null;

	protected WebView webView;
	protected ProgressBar progressView;
	private Button btnMore;
	private View layoutForError;

	protected String urlFromIntent;
	private String titleFromIntent;
	private boolean forSafeFromIntent;

    /**
     * 本方法由父类中的 {@link #onCreate(Bundle)} 方法调用，重写本方法可以实现额外的逻辑。
     */
    @Override
    protected void init(Bundle savedInstanceState)
    {
        super.init(savedInstanceState);

//		initDataFromIntent();
//		initViews();
//		initListeners();
		initDatas();
	}

	/**
	 * 从Intent中读取传递过来的数据。
	 */
	protected void initDataFromIntent()
	{
		//解析从intent中传过来的数据
		ArrayList intentDatas = IntentFactory.parseCommonWeb2Intent(getIntent());
		urlFromIntent = (String)intentDatas.get(0);
		titleFromIntent = (String)intentDatas.get(1);
        forSafeFromIntent = (boolean)intentDatas.get(2);
	}

    /**
     * 本方法由父类的 {@link #init(Bundle)} 调用，子类可在此方法中实现ui的初始化。
     */
    @Override
    protected void initViews(Bundle savedInstanceState){
		// 设定自定义标题栏（设定此值即意味着开启自定义标题栏的使用，必须要在setContentView前设定）
		customeTitleBarResId = R.id.common_web_view_activity_titleBar;
		// 养成良好习惯：首先设置主layout，确保后绪的操作中使用到的组件都可以被find到
		setContentView(R.layout.common_web_view_activity);
		// 标题
		setTitle(titleFromIntent);

		// 自定义标题组件配置
		this.btnMore = this.getCustomeTitleBar().getRightGeneralButton();
		this.btnMore.setVisibility(View.VISIBLE);
		this.btnMore.setText("");
		this.btnMore.setBackgroundResource(R.drawable.common_title_btn_more);
        // 关闭按钮的样式
//        this.getCustomeTitleBar().getLeftBackButton().setBackgroundResource(R.drawable.common_title_btn_close);

		webView = findViewById(R.id.common_web_view2_webview);
		progressView = findViewById(R.id.common_web_view_activity_progressbar);
        layoutForError = findViewById(R.id.common_web_view_activity_errorLL);

		WebSettings webSettings = webView.getSettings();
//		webSettings.setUseWideViewPort(true);
		webSettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(true);
		webSettings.setDefaultZoom(ZoomDensity.FAR);
//	    webSettings.setBuiltInZoomControls(true);

		webView.setWebViewClient(new mWebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    //加载完毕进度条消失
                    progressView.setVisibility(View.GONE);
                } else {
                    progressView.setVisibility(View.VISIBLE);
                    //更新进度
                    progressView.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
	}

    /**
     * 本方法由父类的 {@link #init(Bundle)} 调用，子类可在此方法中为各UI功能组件增加事件临听。
     */
    @Override
    protected void initListeners()
	{
		this.btnMore.setOnClickListener(v -> showMoreMenu());
		this.layoutForError.setOnClickListener(v -> reloadPage());
	}

	private void initDatas()
	{
		webView.loadUrl(urlFromIntent);
	}

    private void showErrorHint(boolean toShow)
    {
        if(toShow)
        {
            if(this.layoutForError.getVisibility() != View.VISIBLE)
                this.layoutForError.setVisibility(View.VISIBLE);
        }
        else
        {
            this.layoutForError.setVisibility(View.GONE);
        }
    }

    private void reloadPage()
    {
//        this.showErrorHint(false);
        this.webView.reload();
    }

	private void showMoreMenu()
    {
        // 实例化menuWindowFor3rdNavi
        if(menuWindowForMore == null)
        {
            // 为选项弹出窗口实现监听类
            View.OnClickListener itemsOnClickForSendPic = new View.OnClickListener(){
                public void onClick(View v)
                {
                    menuWindowForMore.dismiss();

                    try{
                        switch (v.getId())
                        {
                            case R.id.common_web_activity_more_choice_dialog_btn_reload:
                            {
                                reloadPage();
                                break;
                            }
                            case R.id.common_web_activity_more_dialog_btn_pick_copy:
                            {
                                if(forSafeFromIntent){
                                    WidgetUtils.showWithDialog(CommonWebActivity2.this, $$(R.string.general_prompt)
                                            , $$(R.string.common_web_activity_more_choice_safe_hint));
                                }
                                else {
                                    com.eva.android.ToolKits.copyTextToClipborad(CommonWebActivity2.this, urlFromIntent);
                                    WidgetUtils.showToast(CommonWebActivity2.this
                                            , $$(R.string.common_web_activity_more_choice_copy_ok_hint), WidgetUtils.ToastType.OK);
                                }
                                break;
                            }
                            case R.id.common_web_activity_more_dialog_btn_pick_openwith:
                            {
                                if(forSafeFromIntent) {
                                    WidgetUtils.showWithDialog(CommonWebActivity2.this, $$(R.string.general_prompt)
                                            , $$(R.string.common_web_activity_more_choice_safe_hint));
                                }
                                else {
                                    com.eva.android.ToolKits.openWithSystemBrowsers(CommonWebActivity2.this, urlFromIntent);
                                }
                                break;
                            }
                            default:
                                break;
                        }
                    }
                    catch (Exception e){
                        Log.w(TAG, e);
                        WidgetUtils.showWithDialog(CommonWebActivity2.this
                                , $$(R.string.general_prompt), $$(R.string.general_error));
                    }
                }
            };
            menuWindowForMore = new MorenChoicePopWindow(CommonWebActivity2.this, itemsOnClickForSendPic);
        }
        //显示窗口
        menuWindowForMore.showAtLocation(this.btnMore
                , Gravity.BOTTOM| Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
    }

	/**
	 * 捕获back键.
	 */
	@Override
	public void onBackPressed()
	{
		if (webView.canGoBack())
			webView.goBack(); //goBack()表示返回WebView的上一页面
		else
			super.onBackPressed();
	}

	private class mWebViewClient extends WebViewClient
	{
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url)
		{
            // 指明要加载的页面
			view.loadUrl(url);
            // 返回true表示强制使用当前webView 显示网页内容，而不跳转到默认浏览器
			return true;
		}

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
        {
		    Log.e(TAG, "WEB【onReceivedError1】errorCode="+errorCode+"， description="+description);
            showErrorHint(true);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
        {
            Log.e(TAG, "WEB【onReceivedHttpError】getStatusCode="+errorResponse.getStatusCode());
//          showErrorHint(true);
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error)
        {
            Log.e(TAG, "WEB【onReceivedError2】getErrorCode="+error.getErrorCode());
            showErrorHint(true);
            super.onReceivedError(view, request, error);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            switch (error.getPrimaryError()) {
                case SslError.SSL_UNTRUSTED:
                    Log.w(TAG, "WEB【onReceivedSslError】SslError : The certificate authority is not trusted.");
                    break;
                case SslError.SSL_EXPIRED:
                    Log.w(TAG, "WEB【onReceivedSslError】SslError : The certificate has expired.");
                    break;
                case SslError.SSL_IDMISMATCH:
                    Log.w(TAG, "WEB【onReceivedSslError】The certificate Hostname mismatch.");
                    break;
                case SslError.SSL_NOTYETVALID:
                    Log.w(TAG, "WEB【onReceivedSslError】The certificate is not yet valid.");
                    break;
            }

            // 解决在Android 5.0及以上版本时，WebView不能加载https内容的问题，
            // 参考资料：https://blog.csdn.net/LABLENET/article/details/52683893
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//              view.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
                handler.proceed();
            }
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon)
        {
            super.onPageStarted(view, url, favicon);
            Log.e(TAG, "WEB【onPageStarted】"+url);
            showErrorHint(false);
        }

        @Override
        public void onPageFinished(WebView view, String url)
        {
            super.onPageFinished(view, url);
            Log.e(TAG, "WEB【onPageFinished】");
        }
	}


    /**
     * 更多选择的选择窗口.
     *
     * @author Jack Jiang
     * @since 6.0
     */
    private static class MorenChoicePopWindow extends ChoiceItemPopWindow
    {
        private Button btn_reload, btn_copy, btn_openwith, btn_cancel;

        public MorenChoicePopWindow(Activity context, View.OnClickListener mItemsOnClick)
        {
            super(context, mItemsOnClick
                    , R.layout.common_web_activity_more_choice_dialog
                    , R.id.common_web_activity_more_choice_dialog_pop_layout);

            // 以下两行代码将在输入法已经显示的情况下，打开弹窗时能自动隐藏输入法（否则输入法会挡住弹窗）
            setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        }

        protected void initContentViewComponents(View mMenuView)
        {
            btn_reload = mMenuView.findViewById(R.id.common_web_activity_more_choice_dialog_btn_reload);
            btn_copy = mMenuView.findViewById(R.id.common_web_activity_more_dialog_btn_pick_copy);
            btn_openwith = mMenuView.findViewById(R.id.common_web_activity_more_dialog_btn_pick_openwith);
            btn_cancel = mMenuView.findViewById(R.id.common_web_activity_more_dialog_btn_cancel);

            // 取消按钮
            btn_cancel.setOnClickListener(createCancelClickListener());
            // 设置按钮监听
            btn_reload.setOnClickListener(mItemsOnClick);
            btn_copy.setOnClickListener(mItemsOnClick);
            btn_openwith.setOnClickListener(mItemsOnClick);
        }
    }
}
